package com.sy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sy.dto.*;
import com.sy.entity.ClassMsg;
import com.sy.entity.Score;
import com.sy.dto.*;
import com.sy.entity.*;
import com.sy.exception.BusinessException;
import com.sy.service.TeacherService;
import com.sy.vo.ScoreVo;
import com.sy.vo.SearchStuByKeywordsVo;
import com.sy.vo.TeaInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sy.constant.RegConstant.PHONE_REGEX;
import static org.springframework.http.HttpStatus.BAD_REQUEST;

@Service
public class TeacherServiceImpl extends BaseServiceImpl implements TeacherService {

    @Override
    public TeaInfo getTeaInfo(String id) {
        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
        }
        return teacherMapper.getTeaInfoById(id);
    }

    @Override
    public TeaSimpleInfo getTeaSimpleInfo(String studentId) {
        return teacherMapper.getTeaSimpleInfo(studentId);
    }

    @Override
    public boolean updateTeaInfo(TeaInfoVo teaInfoVo) {
        String id = teaInfoVo.getId();
        String name = teaInfoVo.getName();
        String phone = teaInfoVo.getPhone();
        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
        }

        if (!phone.matches(PHONE_REGEX)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }

        teacherMapper.updateTeaInfo(teaInfoVo);
        return true;
    }


    @Override
    public Page<StudentMagTable> getStudentListByTeacherIdForPage(Integer teacherId, Integer page, Integer limit) {
        List<Integer> classIdList = getClassIdListByTeacherId(teacherId);
        //分页组件
        PageHelper.startPage(page, limit);
        //返回Page<>,内有搜索的全部数据
        Page<StudentMagTable> pageResult = (Page<StudentMagTable>) studentMapper.getStudentListByClassIds(classIdList);
        return pageResult;
    }

    @Override
    public List<StudentMagTable> getStudentListByKeyWords(String studyNoSearch, String nameSearch, Integer teacherId) {
        List<Integer> classIdList = getClassIdListByTeacherId(teacherId);
        List<StudentMagTable> studentList = studentMapper.getStudentListByKeyWords(nameSearch, studyNoSearch, classIdList);
        return studentList;
    }


    @Override
    public Page<StudentMagTable> getStudentListByKeyWords(SearchStuByKeywordsVo vo) {
        List<Integer> classIdList = getClassIdListByTeacherId(vo.getTeacherId());
        PageHelper.startPage(vo.getPage(), vo.getLimit());
        Page<StudentMagTable> studentList = (Page<StudentMagTable>) studentMapper.getStudentListByKeyWords(vo.getName(), vo.getStudyNo(), classIdList);
        return studentList;
    }

    @Override
    public List<Integer> getStudentsIdListByTeacherId(Integer teacherId) {
        List<Integer> classIdList = getClassIdListByTeacherId(teacherId);
        List<StudentMagTable> studentList = studentMapper.getStudentListByClassIds(classIdList);
        ArrayList<Integer> studentsIdList = new ArrayList<>();
        for (StudentMagTable student : studentList) {
            studentsIdList.add(student.getId());
        }
        return studentsIdList;
    }

    @Override
    public Page<HomeworkCheckTab> getCheckHomeworkTable(Integer teacherId, Integer page, Integer limit) {
        //先获取该老师下的所有学生id
        List<Integer> studentsIdList = getStudentsIdListByTeacherId(teacherId);
        System.out.println("--------------------该老师下的所有学生id-----------------------");
        System.out.println(studentsIdList);
        //根据学生的id获取已提交作业的学生id和作业id
        List<SubmitStudentMsg> hasSubmitStudentsMsg = homeworkMapper.getHasSubmitStudentsMsg(studentsIdList);
        System.out.println("--------------------获取已提交作业的学生id和作业id----------------------");
        System.out.println(hasSubmitStudentsMsg);
        //遍历已提交作业的学生和作业信息
        for (SubmitStudentMsg submitStudentMsg : hasSubmitStudentsMsg) {
            Score score = scoreMapper.getScoreByStudentIAndHomeworkId(submitStudentMsg);
            if (Objects.isNull(score)) {
                //如果没有查找到说明分数表没有数据,插入数据
                scoreMapper.addScoreByHasSubmit(submitStudentMsg);
            }
        }
        //获取分数表中已提交作业的学生的信息列表
        PageHelper.startPage(page, limit);
        Page<HomeworkCheckTab> scoreList = (Page<HomeworkCheckTab>) scoreMapper.getScoreBySubmitStudentsId(hasSubmitStudentsMsg);
        System.out.println("--------------------已提交作业的学生的信息列表---------------------");
        System.out.println(scoreList);
        return scoreList;

    }

    @Override
    public CheckHomeworkDetailTab getCheckHomeworkDetail(Integer scoreId, Integer homeworkId, Integer studentId) {
        CheckHomeworkDetailTab checkHomeworkDetailTab = new CheckHomeworkDetailTab();
        //获得作业的标题
        Homework homework = homeworkMapper.getHomeworkById(homeworkId);
        //获得作业的简答题
        ShortQuestion shortQuestion = homeworkMapper.getShortQuestionByHomeworkId(homeworkId);
        //获得简答题的答案
        SubmitShortAnswer submitShortAnswer = homeworkMapper.getSubmitShortAnswer(homeworkId, studentId);
        //获得简答题正确的数目
        Integer countForTrue = homeworkMapper.getCountForTrue(homeworkId, studentId);
        if(!(Objects.isNull(homework)&&Objects.isNull(shortQuestion)&&Objects.isNull(submitShortAnswer)&&Objects.isNull(countForTrue))){

        checkHomeworkDetailTab.setTitle(homework.getTitle());
        checkHomeworkDetailTab.setShortQuestion(shortQuestion.getQuestion());
        checkHomeworkDetailTab.setShortAnswer(submitShortAnswer.getAnswer());
        checkHomeworkDetailTab.setChoiceTrueCount(countForTrue);
    }else {
            throw new BusinessException(HttpStatus.NOT_FOUND,"作业没有找到.......");
        }

        return checkHomeworkDetailTab;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED
            , rollbackFor = {BusinessException.class})
    public void inputScore(Integer teacherId,Integer scoreId, ScoreVo scoreVo) {
        //根据老师id获取老师
        Teacher teacher = teacherMapper.getTeacherById(String.valueOf(teacherId));
        //老师姓名
        String name = teacher.getName();
        //更新数据
        boolean isUpdate = scoreMapper.updateScoreById(scoreId, scoreVo, name);
        if(!isUpdate){
            throw new BusinessException(HttpStatus.NOT_FOUND,"操作失败.......");
        }
    }

    @Override
    public ClassMsg getClassMsgById(Integer classId) {
        return classMsgMapper.getClassById(classId);
    }

    @Override
    public List<ClassMsg> getClassListByTeacherId(Integer teacherId) {
        List<ClassMsg> classList = classMsgMapper.getClassListByTeacherId(teacherId);
        return classList;
    }

    @Override
    public List<Integer> getClassIdListByTeacherId(Integer teacherId) {
        List<ClassMsg> classList = getClassListByTeacherId(teacherId);
        ArrayList<Integer> classIds = new ArrayList<>();
        for (ClassMsg classMag : classList) {
            classIds.add(classMag.getId());
        }
        return classIds;
    }

}
